<script setup>
import { ref, reactive, onMounted, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  // 表格数据API
  listApi: {
    type: Function,
    required: true
  },
  // 获取单条数据API
  getApi: {
    type: Function,
    required: true
  },
  // 添加数据API
  addApi: {
    type: Function,
    required: true
  },
  // 更新数据API
  updateApi: {
    type: Function,
    required: true
  },
  // 删除数据API
  delApi: {
    type: Function,
    required: true
  },
  // 表格列配置
  columns: {
    type: Array,
    required: true
  },
  // 表格标题
  title: {
    type: String,
    default: '数据管理'
  }
})

const emit = defineEmits(['refresh'])

// 表格数据
const tableData = ref([])
// 分页信息
const pagination = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// 查询参数
const queryParams = ref({})

// 表单数据
const formData = ref({})

// 表单对话框可见性
const dialogVisible = ref(false)
// 表单操作类型（add/edit）
const formType = ref('')

// 加载状态
const loading = ref(false)

// 获取表格数据
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams.value
    }
    const res = await props.listApi(params)
    tableData.value = res || res.data || []
  } catch (error) {
    console.error('获取数据失败', error)
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handlePageChange = (page) => {
  pagination.currentPage = page
  getList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getList()
}

// 重置表单
const resetForm = () => {
  formData.value = {}
}

// 打开添加对话框
const handleAdd = () => {
  resetForm()
  formType.value = 'add'
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = async (row) => {
  resetForm()
  formType.value = 'edit'
  try {
    const res = await props.getApi(row.id)
    formData.value = res.data || res
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败', error)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    if (formType.value === 'add') {
      await props.addApi(formData.value)
      ElMessage.success('添加成功')
    } else {
      await props.updateApi(formData.value)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    getList()
    emit('refresh')
  } catch (error) {
    console.error('提交失败', error)
  }
}

// 删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该条数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await props.delApi(row.id)
      ElMessage.success('删除成功')
      getList()
      emit('refresh')
    } catch (error) {
      console.error('删除失败', error)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 刷新数据
const refresh = () => {
  pagination.currentPage = 1
  getList()
}

// 组件挂载时获取数据
onMounted(() => {
  getList()
})

// 暴露方法给父组件
defineExpose({
  refresh
})
</script>

<template>
  <div class="crud-container">
    <div class="crud-header">
      <h2>{{ title }}</h2>
      <div class="crud-actions">
        <el-button type="primary" @click="handleAdd">添加</el-button>
        <el-button @click="refresh">刷新</el-button>
      </div>
    </div>

    <el-table :data="tableData" v-loading="loading" border style="width: 100%">
      <el-table-column v-for="(column, index) in columns" :key="index" :prop="column.prop" :label="column.label" :width="column.width">
        <template #default="scope" v-if="column.formatter">
          {{ column.formatter(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog
      :title="formType === 'add' ? '添加数据' : '编辑数据'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item v-for="(column, index) in columns.filter(col => !col.hideInForm)" :key="index" :label="column.label">
          <el-input v-model="formData[column.prop]" :placeholder="`请输入${column.label}`" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.crud-container {
  padding: 20px;
}

.crud-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.crud-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>